package com.huoshan.im.server.action.support;

import com.alibaba.fastjson.JSONObject;
import com.huoshan.im.server.ContextNaming;
import lombok.extern.slf4j.Slf4j;
import online.chazi.netkit.messaging.Message;

import java.lang.reflect.ParameterizedType;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 火山九日 on 2020-04-26 09:49
 */
@Slf4j
public abstract class JsonActionSupport<T> extends ActionSupport {

    private byte extension;

    public byte getExtension() {
        return this.extension;
    }

    public void execute(Message message) {

        try {
            final String content = message.messageContentAsString();
            log.debug("messageId={},content={}", message.getMessageId(), content);
            T t = JSONObject.parseObject(content, ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
            this.extension = message.getExtension();
            execute(t);
        } catch (Exception e) {
            // 由于action的执行是提交到线程池执行, Exception无法被ChannelListener捕捉到, 会存在一直发错误的登录请求的恶意连接
            AtomicInteger errCount = (AtomicInteger) getSession().getAttribute(ContextNaming.CHANNEL_EXCEPTION_CAUGHT_COUNT);
            if (errCount.incrementAndGet() > 2) {
                getSession().getChannel().close();
            }
            throw e;
        }

    }

    public abstract void execute(T t);

}
